package com.doudanhua.basecode.jackson.configurer;

import com.doudanhua.basecode.jackson.time.DateTimeConverter;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.node.TextNode;

import java.io.IOException;
import java.util.Date;

/**
 * @Author zhangqian
 * @Description TODO
 * @Date 2022/11/4 17:24
 */
public class DateModelDeserializer extends JsonDeserializer<Date> {
    private DateTimeConverter _dateConverter;

    public DateModelDeserializer(DateTimeConverter dateConverter) {
        this._dateConverter = dateConverter;
    }

    @Override
    public Date deserialize(JsonParser jp, DeserializationContext dc) throws IOException {
        // 兼容 long 类型
        if (jp.getCurrentTokenId() == JsonTokenId.ID_NUMBER_INT) {
            long ts;
            try {
                ts = jp.getLongValue();
            } catch (JsonParseException e) {
                Number v = (Number) dc.handleWeirdNumberValue(Date.class, jp.getNumberValue(),
                        "not a valid 64-bit long for creating `java.util.Date`");
                ts = v.longValue();
            }
            return new java.util.Date(ts);
        }
        ObjectCodec codec = jp.getCodec();
        TextNode node = codec.readTree(jp);
        String dateString = node.textValue();
        return _dateConverter.parseDate(dateString);
    }
}
